package com.cie2.janji.pages.users;

import java.util.List;

import org.apache.log4j.Logger;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.PropertyAccess;

import com.cie2.janji.base.CieUserPage;
import com.cie2.janji.entities.Category;
import com.cie2.janji.models.EasyIdSelectModel;
import com.cie2.janji.services.CategoryService;

public class CreateCategory extends CieUserPage {

	static Logger logger = Logger.getLogger(CreateCategory.class.getName());

	@SuppressWarnings("unused")
	@Property
	@Persist
	private EasyIdSelectModel<Category> categoryModels;

	@Property
	private Long categoryId;

	@Property
	private Category category;

	// services
	@Inject
	private CategoryService categoryService;

	@Inject
	private PropertyAccess propertyAccess;

	Long onPassivate() {
		return categoryId;
	}

	void onActivate(Long categoryId) {
		this.categoryId = categoryId;
		category = categoryService.load(categoryId);
	}

	/**
	 * kenapa kalo extends cie user page, selectnya gak nongol ? 
	 * gara2 on activatenya ada di base kah ? 
	 *
	 */
	void onActivate() {
		refreshCategory();
	}

	void refreshCategory() {
				List<Category> categories = categoryService.getAll();
				logger.info("Refresh category size : " + categories.size());
				categoryModels = new EasyIdSelectModel<Category>(categories, Category.class, "name", "id", propertyAccess);
	}

	@CommitAfter
	Object onSuccess() {
//		if (categoryId != null) {
//			Category parentCategory = categoryService.load(categoryId);
//		}
		
		if(null == categoryId)
			categoryService.add(category);
		else
			categoryService.update(category);
		
		return CategoryList.class;
	}
}
